
import User from "@/db/models/user";

// 加密
import crypto from "crypto";
import { LoginRequest } from "@/types/service";
import { CustomResponse } from "@/middleware/error";

import jwt from "jsonwebtoken";

export const login = async (req: LoginRequest, res: CustomResponse) => {
  if (!req.body || !req.body.email || !req.body.password) {
    res.cc("email and password are required!");
    return;
  }
  let email = req.body.email;
  let password = req.body.password;

  const hash = crypto.createHash("md5");
  password = hash.update(password).digest("hex");

  const result = await User.findOne({
    where: {
      email,
      password,
    },
  });
  if (!result) return res.cc("User not found!");

  // 生成token
  const tokenStr = jwt.sign({
    id: result!.id,
    email: result!.email,
    username: result!.username,
    password: result!.password,
  }, (await import("config")).default.secret, {
    expiresIn: (await import("config")).default.expiresIn,
  })

  res.send({
    status: 200,
    token: 'Bearer ' + tokenStr, // OAuth 2.0标准中规定的令牌类型前缀
    msg: '登录成功'
  });
};
